//
//  PublishVC.m
//  TuYouAPP
//
//  Created by L on 14-2-19.
//
//

#import "PublishVC.h"
#import "PublishSuccessVC.h"
#import "DataModel.h"
#import "DataModel.h"
#import "QiniuSimpleUploader.h"
#import "Util.h"
#import "QiniuConfig.h"
#import "JSONKit.h"
@interface PublishVC ()
{
    UIButton *tempBtn;
    UIView *photoView;
    NSMutableArray *imgArray;
    float photoX;
    float orignY;
    UIView *MymapView;
    UIButton *addBtn;
    UITextView *textview;
    UIGestureRecognizer *tapGesture;
    MWPhotoBrowser *browser;
    NSMutableArray *points;
    MAPinAnnotationView*annotationView;
    UILabel *mapViewLabel;
    TYUserState *myPublish;
    
    QiniuSimpleUploader* _fileUploader;
    QiniuSimpleUploader* _fileUploader1;
    QiniuSimpleUploader* _fileUploader3;
    QiniuSimpleUploader* _fileUploader4;
    NSMutableArray*     _filejobs;
    NSMutableArray*     _filekeys;
    BOOL    _auser;
    BOOL    _buser;
    BOOL    _cuser;
    void(^_mcallbackblcok)(NSString*,NSString*);
    TYUserState* _thepub;
    NSString*   _nulloj;
    int _nextc;
    NSMutableArray *imageUrlArray;
    UIImageView *pinimage;
    MAPointAnnotation *red ;
    MAPointAnnotation *temp;

}

@end

@implementation PublishVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = ColorRGB(230, 230, 230);
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
-(void)viewDidUnload
{
    _fileUploader = nil;
    _fileUploader1 = nil;
    _fileUploader3 = nil;
    _fileUploader4 = nil;
    _filejobs = nil;
    _filekeys = nil;
    _thepub = nil;
    _nulloj = nil;
}
- (void)viewDidLoad
{
    self.mPageName = @"发布";

    [super viewDidLoad];
	// Do any additional setup after loading the view.
    myPublish = [[TYUserState alloc]init];
    imageUrlArray = [[NSMutableArray alloc]init];
    imgArray = [[NSMutableArray alloc]init];
    self.search = [[AMapSearchAPI alloc] initWithSearchKey:MapAPIKey Delegate:self];
    self.Title = @"发布";
    self.LeftBarTitle = @"取消";
    self.RightBarTitle = @"发送";
    if (SystemIsiOS7()) {
        self.ScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 84, 320, DEVICE_Height-84)];
        self.automaticallyAdjustsScrollViewInsets = NO;

        
    }
    else
    {
        self.ScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, 320, DEVICE_Height-84)];
        
        
    }
    self.ScrollView.backgroundColor = ColorRGB(230, 230, 230);
    [self.view addSubview:self.ScrollView];
    [self loadDataAndView];
    
    _fileUploader = [QiniuSimpleUploader getuploader];
    _fileUploader1 = [QiniuSimpleUploader getuploader];
    _fileUploader3 = [QiniuSimpleUploader getuploader];
    _fileUploader4 = [QiniuSimpleUploader getuploader];
    _filejobs = [[NSMutableArray alloc] init];
    _filekeys = [[NSMutableArray alloc] init];
    _auser = NO;
    _buser = NO;
    _nulloj = @"1";
}


-(void)leftBtnTouched:(id)sender

{
    NSArray *arr = self.navigationController.viewControllers;
    UIViewController *vc;
    if (self.comeFrom == 1) {
        vc = [arr objectAtIndex:0];
    }
    else if (self.comeFrom == 2)
    {
        vc = [arr objectAtIndex:1];
    }
    [self.navigationController popToViewController:vc animated:YES];
}
-(void)rightBtnTouched:(id)sender
{
    [SVProgressHUD showWithStatus:@"发布中"];
    
    if ([textview.text isEqualToString:@"发布在这儿的最新情况,将会对后面的途友提供帮助"]) {
        [SVProgressHUD showErrorWithStatus:@"发送内容不能为空"];
        return;
    }
    if (textview.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"发布内容不能为空"];
        return;
    }
    else
        if ([textview.text isEqualToString:@" "]||[textview.text isEqualToString:@","]||[textview.text isEqualToString:@"，"]) {
            [SVProgressHUD showErrorWithStatus:@"必须为汉字"];
            return;

        }
    myPublish.mPointInfo = mapViewLabel.text;
    myPublish.mContext = textview.text;
    myPublish.mRelInfo = @"景点";
    //可能需要走个进度提示之类的,
    [self prePubish:myPublish callback:^(NSString *err,NSString *objid) {
        
        if( err == nil )
        {
         //   [SVProgressHUD sho]
            [SVProgressHUD showSuccessWithStatus:@"发布成功"];
            
            PublishSuccessVC *vc = [[PublishSuccessVC alloc]init];
            
            vc.imageUrlArray = imageUrlArray;
            vc.ComeFrom = self.comeFrom;
            myPublish.objId = objid;
            
            myPublish.mTaguser = [TYUser currentUser];
            vc.publish = myPublish;
            
            [self.navigationController pushViewController:vc animated:YES];
             }
        else
        {
            [SVProgressHUD showSuccessWithStatus:@"发布失败"];

            //弹出错误信息
        }
    }];
    
}
-(void)realUpFileJob:(NSString*)f
{
    @synchronized(_filejobs)
    {
        [_filejobs addObject:f];
    }
    
    if( !_auser )
    {
        _nextc ++;
        _auser = YES;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString* f = nil;
            NSString* retfilekey = nil;
            NSDictionary* tt = nil;
            NSString* kf = nil;
            int e = 0;
            while ( YES ) {
                @synchronized(_filejobs)
                {
                    f = [_filejobs lastObject];
                    if( f )
                        [_filejobs removeLastObject];
                }
                if( !f ) break;
                retfilekey = [_fileUploader uploadFileSYN:f key:kQiniuUndefinedKey extra:nil];
                tt = [retfilekey objectFromJSONString];
                kf = [tt objectForKey:@"key"];
                if( kf != nil )
                {
                    NSLog(@"thekey:%@",kf);
                    @synchronized(_filekeys)
                    {
                        [_filekeys addObject:kf];
                    }
                }
                else
                {
                    e = 1;
                    break;
                }
                if( ![[NSFileManager defaultManager] removeItemAtPath:f error:nil] )
                {
                    NSLog(@"删除文件出错");
                }
            }
            
            [self nextStep:e];
            
            NSLog(@"end time");
        });
    }
    else if( !_buser )
    {
        _buser = YES;
        _nextc ++;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString* f = nil;
            NSString* retfilekey = nil;
            NSDictionary* tt = nil;
            NSString* kf = nil;
            int e = 0;
            while ( YES ) {
                @synchronized(_filejobs)
                {
                    f = [_filejobs lastObject];
                    if( f )
                        [_filejobs removeLastObject];
                }
                if( !f ) break;
                retfilekey = [_fileUploader1 uploadFileSYN:f key:kQiniuUndefinedKey extra:nil];
                tt = [retfilekey objectFromJSONString];
                kf = [tt objectForKey:@"key"];
                if( kf != nil )
                {
                    NSLog(@"thekey:%@",kf);
                    @synchronized(_filekeys)
                    {
                        [_filekeys addObject:kf];
                    }
                }
                else
                {
                    e = 1;
                    break;
                }
                if( ![[NSFileManager defaultManager] removeItemAtPath:f error:nil] )
                {
                    NSLog(@"删除文件出错");
                }
            }
            [self nextStep:e];
            NSLog(@"end time");
        });
    }
    else if ( !_cuser )
    {
        _cuser = YES;
        _nextc ++;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString* f = nil;
            NSString* retfilekey = nil;
            NSDictionary* tt = nil;
            NSString* kf = nil;
            int e = 0;
            while ( YES ) {
                @synchronized(_filejobs)
                {
                    f = [_filejobs lastObject];
                    if( f )
                        [_filejobs removeLastObject];
                }
                if( !f ) break;
                retfilekey = [_fileUploader3 uploadFileSYN:f key:kQiniuUndefinedKey extra:nil];
                tt = [retfilekey objectFromJSONString];
                kf = [tt objectForKey:@"key"];
                if( kf != nil )
                {
                    NSLog(@"thekey:%@",kf);
                    @synchronized(_filekeys)
                    {
                        [_filekeys addObject:kf];
                    }
                }else
                {
                    e = 1;
                    break;
                }
                if( ![[NSFileManager defaultManager] removeItemAtPath:f error:nil] )
                {
                    NSLog(@"删除文件出错");
                }
            }
           [self nextStep:e];
            NSLog(@"end time");
        });
    }
}
-(void)prePubish:(TYUserState*)pub callback:(void(^)(NSString*,NSString*objid))calla
{
    _mcallbackblcok = calla;
    _thepub = pub;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData* da = nil;
        NSString* f = nil;
        NSString* retfilekey = nil;
        int i = 0;
        BOOL    bret;
        //NSMutableArray* patharr = [[NSMutableArray alloc] init];
        
        CGSize max = CGSizeMake(1024, 1024);
        CGSize it;
        NSLog(@"start time");
        int j = 0;
        int c = (int)pub.mImgArr.count-1;
        int e = 0;
        _thepub = pub;
        _nextc = 1;
        for ( UIImage* oneimg in pub.mImgArr ) {
            NSLog(@"%F%F",oneimg.size.height,oneimg.size.width);
            if( oneimg.size.height > 1024 || oneimg.size.width > 1024 )
            {
                it = [Util scaleIMG:max orgImgSize:oneimg.size];
                UIImage* timg = [Util scaleToSize:oneimg showsize:it];
                NSLog(@"%F%F",timg.size.height,timg.size.width);
                da = UIImageJPEGRepresentation(timg, 0.9f);
                if (da.length >300000) {
                      da = UIImageJPEGRepresentation(timg, 0.85f);
                    if (da.length >300000) {
                        da = UIImageJPEGRepresentation(timg, 0.8f);
                    }
                }
                  NSLog(@"%@",[NSDate date]);
            }
            else
                da = UIImageJPEGRepresentation(oneimg, 0.8f);
            
            f = [Util makeJPGImgFuallPath:i++];
            bret = [da writeToFile:f atomically:YES];
            if( !bret )
            {
                NSLog(@"压缩图片失败!");
                e = 1;
                break;
            }

            j++;
            if( j == c )
            {
                retfilekey = [_fileUploader4 uploadFileSYN:f key:kQiniuUndefinedKey extra:nil];
            }
            else
            {
                [self realUpFileJob:f];
                continue;
            }
            if( retfilekey == nil )
            {//上传失败
                NSLog(@"上传图片失败!");
                e = 1;
                break;
            }
            
            NSDictionary* tt = [retfilekey objectFromJSONString];
            NSString* kf = [tt objectForKey:@"key"];
            if( kf == nil )
            {
                NSLog(@"上传图片失败!");
                e = 1;
                break;
            }
            
            if( ![[NSFileManager defaultManager] removeItemAtPath:f error:nil] )
            {
                NSLog(@"删除文件出错");
            }
            
            @synchronized(_filekeys)
            {
                [_filekeys addObject:kf];
            }
        }
        if( e )
        {
            if( ![[NSFileManager defaultManager] removeItemAtPath:f error:nil] )
            {
                NSLog(@"删除文件出错");
            }
        }
        [self nextStep:e];
    });
    
}
-(void)nextStep:(int)e
{
    @synchronized(_nulloj)
    {
        if( e )
        {
            if( _mcallbackblcok )
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    _mcallbackblcok(@"上传文件失败",nil);
                    _mcallbackblcok = nil;
                });
            }
        }
        else
        {
            _nextc --;
            if( _nextc == 0 )
            {
                imageUrlArray = _filekeys;
                [TYUserState publishState:_itpoint pointinfo:_thepub.mPointInfo txt:_thepub.mContext imgArr:_filekeys callback:^(NSString *erra,NSString *objid) {
                    _mcallbackblcok(erra,objid);
                }];
            }
        }
    }
}

-(void)loadDataAndView
{
     orignY = 0.0F;
    UIView *publishTopView  = [[UIView alloc]initWithFrame:CGRectMake(9, orignY, 302, 100)];
    publishTopView.layer.borderWidth = 0.5;
    publishTopView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];;
    textview = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 300, 100)];
    textview.backgroundColor = [UIColor clearColor];
    textview.text = @"发布在这儿的最新情况,将会对后面的途友提供帮助";
    textview.delegate = self;
    textview.returnKeyType = UIReturnKeyDone;
    textview.textColor = [UIColor grayColor];
    textview.font = [UIFont systemFontOfSize:15];
    [publishTopView addSubview:textview];
    publishTopView.backgroundColor = [UIColor whiteColor];
    [self.ScrollView addSubview:publishTopView];
    orignY += 115;
    UIView *publishTypeView = [[UIView alloc]initWithFrame:CGRectMake(9, orignY, 302, 40)];
   // publishTypeView.backgroundColor = [UIColor whiteColor];
    float x =0.0f;
    for (int i =0; i<4; i++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(x  ,0 , 74, 40)];
        [button addTarget:self action:@selector(typeBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i+10;
        [button setBackgroundColor:[UIColor whiteColor]];
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(x+10, 7, 25, 25)];
        image.tag = i+100;
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x+10+28, 5, 40, 30)];
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        
        if (i == 0) {
            image.image = [UIImage imageNamed:@"jiaotong.png"];
            label.text = @"交通";
        }
        else if (i == 1)
        {
            image.image = [UIImage imageNamed:@"jingdian.png"];
            label.text = @"景点";

        }
        else if (i == 2)
        {
            image.image = [UIImage imageNamed:@"zhushu.png"];
            label.text = @"住宿";

        }
        else if (i == 3)
        {
            image.image = [UIImage imageNamed:@"meishi.png"];
            label.text = @"美食";

        }
        [publishTypeView addSubview:button];
        [publishTypeView addSubview:image];
        [publishTypeView addSubview:label];
        x += 75;
    }
   // [self.ScrollView addSubview:publishTypeView];
   // orignY += 55;
    
    [self loadPhotoView];
    
    [self loadMapView];
    self.ScrollView.contentSize  = CGSizeMake(320, orignY);

    NSLog(@"%f",orignY);
}

-(void)loadPhotoView
{
    photoView = [[UIView alloc]initWithFrame:CGRectMake(9, orignY, 302, 80)];
    photoView.layer.borderWidth = 0.5;
    photoView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];;
     photoX = 10.0f;
    addBtn = [[UIButton alloc]initWithFrame:CGRectMake(photoX, 10, 60, 60)];
    photoX += 72;
    [addBtn setImage:[UIImage imageNamed:@"tianjiatupian.png"] forState:UIControlStateNormal];

    [addBtn addTarget:self action:@selector(photoBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
    [photoView addSubview:addBtn];
    orignY +=95;
    photoView.backgroundColor = [UIColor whiteColor];
    [self.ScrollView addSubview:photoView];

    
}
-(void)backgroundTaped:(UIGestureRecognizer *)ges
{
    [textview resignFirstResponder];
}
#pragma  textViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; {
    
    if ([@"\n" isEqualToString:text] == YES) {
        [textview resignFirstResponder];
        return NO;
    }
    return YES;
}


-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"发布在这儿的最新情况,将会对后面的途友提供帮助"]) {
        textView.text = @"";

    }
    textView.textColor = [UIColor blackColor];
       tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTaped:)];
    [self.ScrollView addGestureRecognizer:tapGesture];
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    myPublish.mContext = textView.text;
    [self.ScrollView removeGestureRecognizer:tapGesture];
}
-(void)loadMapView
{
    points  = [[NSMutableArray alloc]init];
    MymapView = [[UIView alloc]initWithFrame:CGRectMake(10, orignY, 300, DEVICE_Height-orignY-90)];
    MymapView.layer.borderWidth = 0.5;
    MymapView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    MymapView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(8, 10, 15, 20)];
    mapViewLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 5, 225, 30)];
    mapViewLabel.numberOfLines = 0;
  //  [mapViewLabel sizeToFit];
    

    //mapViewLabel.text = @"重庆市,渝北区,花园路";
    mapViewLabel.minimumScaleFactor = 0.5;
    mapViewLabel.font = [UIFont systemFontOfSize:12];
    [MymapView addSubview:mapViewLabel];
    image.image = [UIImage imageNamed:@"tubiao.png"];
    UIButton *refreshbtn = [[UIButton alloc]initWithFrame:CGRectMake(260, 10, 20, 20)];
    [refreshbtn setImage:[UIImage imageNamed:@"shuaxin.png"] forState:UIControlStateNormal];
    [refreshbtn addTarget:self action:@selector(RefreshBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
    [MymapView addSubview:refreshbtn];
    [MymapView addSubview:image];
    self.MaMapView=[[MAMapView alloc] initWithFrame:CGRectMake(5, 40, 290, MymapView.frame.size.height - 45)];
    pinimage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 48, 68)];
    pinimage.hidden = YES;
    pinimage.image = [UIImage imageNamed:@"purplePin.png"];
    [self.MaMapView addSubview:pinimage];
    
    pinimage.center = self.MaMapView.center;
    CGRect rect = pinimage.frame;
    rect.origin.y -= 38;
    rect.origin.x -= 5;
    pinimage.frame = rect;
    self.MaMapView.delegate = self;
    self.MaMapView.showsUserLocation = YES;
   // self.MaMapView.showsCompass= YES;         //关闭指南针
 //   UIGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(LongPressed:)];
   // [self.MaMapView addGestureRecognizer:longpress];
    
    [self.MaMapView setZoomLevel:16.0 animated:YES];

    [MymapView addSubview:self.MaMapView];

    
    
    orignY += 200;
    [self.ScrollView addSubview:MymapView];
}
-(void)RefreshBtnTouched:(id)sender
{
    self.MaMapView.showsUserLocation = YES;
}
-(void)LongPressed:(UIGestureRecognizer*)ges
{
    if (ges.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [ges locationInView:self.MaMapView];
        // NSLog(@"%f,%f",point.x,point.y);
        CLLocationCoordinate2D coordinate = [self.MaMapView convertPoint:point toCoordinateFromView:self.MaMapView];
        _itpoint = coordinate;
        NSLog(@"lat:%f lon:%f",coordinate.latitude,coordinate.longitude);
        
        
        AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
        regeoRequest.searchType = AMapSearchType_ReGeocode;
        regeoRequest.location = [AMapGeoPoint  locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
        regeoRequest.radius = 10000;
        regeoRequest.requireExtension = NO;
        [self.search AMapReGoecodeSearch: regeoRequest];
        
        red = [[MAPointAnnotation alloc] init];
        red.coordinate = coordinate;
        red.title  = @"当选选中";
        [points addObject:red];
        [self.MaMapView addAnnotations: points];
        
    }
 
}

#pragma 地图搜索
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    NSString *result = [NSString stringWithFormat:@"%@", response.regeocode.formattedAddress];
    mapViewLabel.text = result;
    NSLog(@"省%@,市%@,区%@",response.regeocode.addressComponent.province,response.regeocode.addressComponent.city,response.regeocode.addressComponent.district);
    myPublish.mPointInfo = result;
    
  //  NSLog(@"ReGeo: %@", result);
}
#pragma 更新位置
 -(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    //NSLog(@"endend");
    
    pinimage.hidden = YES;
    red = [[MAPointAnnotation alloc] init];
    CGPoint point = mapView.center;
    point.x-= 5;
    point.y-= 38;
    CLLocationCoordinate2D coordinate = [mapView convertPoint:point toCoordinateFromView:mapView];
    red.coordinate = coordinate;
    _itpoint = coordinate;
    red.title  = @"当选选中";
   // [points addObject:red];
    
    AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
    regeoRequest.searchType = AMapSearchType_ReGeocode;
    regeoRequest.location = [AMapGeoPoint  locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeoRequest.radius = 10000;
    regeoRequest.requireExtension = NO;
    [self.search AMapReGoecodeSearch: regeoRequest];
    
    
    [mapView addAnnotation:red];
    
}
- (void)mapView:(MAMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    [self.MaMapView  removeAnnotation:temp];

    pinimage.hidden = NO;
}
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation

{

    self.MaMapView.showsUserLocation = NO;
    //搜索
    AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
    regeoRequest.searchType = AMapSearchType_ReGeocode;
    regeoRequest.location = [AMapGeoPoint  locationWithLatitude:userLocation.coordinate.latitude longitude:userLocation.coordinate.longitude];
    regeoRequest.radius = 10000;
    
    regeoRequest.requireExtension = NO;
    [self.search AMapReGoecodeSearch: regeoRequest];

    [self.MaMapView setCenterCoordinate:userLocation.coordinate animated:YES];

  //  [self.MaMapView addAnnotation:red];
       // self.MaMapView.zoomLevel = 8.0f;
    // isSet = !isSet;

}

#pragma 地图标注

-(void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view didChangeDragState:(MAAnnotationViewDragState)newState fromOldState:(MAAnnotationViewDragState)oldState
{
    if (view.dragState == MAAnnotationViewDragStateStarting) {
        
        NSLog(@"%F,%F",view.annotation.coordinate.latitude,view.annotation.coordinate.longitude);
    }
   else if (view.dragState == MAAnnotationViewDragStateNone) {
       
       AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
       regeoRequest.searchType = AMapSearchType_ReGeocode;
       
       _itpoint = view.annotation.coordinate;
       
       regeoRequest.location = [AMapGeoPoint  locationWithLatitude:view.annotation.coordinate.latitude longitude:view.annotation.coordinate.longitude];
       regeoRequest.radius = 10000;
       regeoRequest.requireExtension = NO;
       [self.search AMapReGoecodeSearch: regeoRequest];
       
       NSLog(@"stop:%F,%F",view.annotation.coordinate.latitude,view.annotation.coordinate.longitude);
   }
 
    
    
}
-(MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        [self.MaMapView  removeAnnotation:temp];
        temp = red;

        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
            annotationView.canShowCallout= YES;      //设置气泡可以弹出，默认为NO
            annotationView.animatesDrop = YES;       //设置标注动画显示，默认为NO
            annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
          //  annotationView.rightCalloutAccessoryView=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];  //设置气泡右侧按钮
            
        }
       // annotationView.pinColor = [self.annotations indexOfObject:annotation];
        return annotationView;
        
    }  
    return nil;  
}

-(void)typeBtnTouched:(UIButton *)sender
{
//    static BOOL isFirst = NO;
//    if (!isFirst) {
//        
//    }
    if (tempBtn && tempBtn.tag == sender.tag) {
        
        return;
    }
    UIView *view = (UIView*)sender.superview;
    int lastTag = tempBtn.tag +90;
    int nowTag = sender.tag +90;
    if (lastTag==100) {
        UIImageView *lastimage = (UIImageView*)[view viewWithTag:lastTag];
        lastimage.image = [UIImage imageNamed:@"jiaotong.png"];
       
        
    }
    else if (lastTag == 101)
    {
        UIImageView *lastimage = (UIImageView*)[view viewWithTag:lastTag];
        lastimage.image = [UIImage imageNamed:@"jingdian.png"];

    }
    else if (lastTag == 102)
    {
        UIImageView *lastimage = (UIImageView*)[view viewWithTag:lastTag];
        lastimage.image = [UIImage imageNamed:@"zhushu.png"];

    }
    else if (lastTag == 103)
    {
        UIImageView *lastimage = (UIImageView*)[view viewWithTag:lastTag];
        lastimage.image = [UIImage imageNamed:@"meishi.png"];

    }

    if (nowTag==100) {

        UIImageView *nowimage = (UIImageView*)[view viewWithTag:nowTag];
        nowimage.image = [UIImage imageNamed:@"jiaotong_xuanzhong.png"];
        
    }
    else if (nowTag == 101)
    {

        UIImageView *nowimage = (UIImageView*)[view viewWithTag:nowTag];
        nowimage.image = [UIImage imageNamed:@"jingdian_xuanzhong.png"];
    }
    else if (nowTag == 102)
    {

        UIImageView *nowimage = (UIImageView*)[view viewWithTag:nowTag];
        nowimage.image = [UIImage imageNamed:@"zhushu_xuanzhong.png"];
    }
    else if (nowTag == 103)
    {

        UIImageView *nowimage = (UIImageView*)[view viewWithTag:nowTag];
        nowimage.image = [UIImage imageNamed:@"meishi_xuanzhong.png"];
    }
    
    tempBtn = sender;

}
-(void)photoBtnTouched:(UIButton *)sender
{
    if (imgArray.count == 9 ) {
        [SVProgressHUD showErrorWithStatus:@"最多只能选择9张"];
        return ;
    }
    UIActionSheet *ac = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
    ac.tag = 1001;
    [ac showInView:[self.view window]];

}
#pragma mark -
#pragma mark UIActionSheet && UIAlertView Delegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != 2) {
        
        [self startImagePickerVCwithButtonIndex:buttonIndex];
        
    }
    
}
- (void)startImagePickerVCwithButtonIndex:(NSInteger )buttonIndex
{
    int type;
    
    
    if (buttonIndex == 0) {
        type = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = type;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
     //   imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:^{
            
        }];

    }
    else if(buttonIndex == 1){
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.limitsMaximumNumberOfSelection = YES;
        imagePickerController.maximumNumberOfSelection = 9;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];


    }
    
    
    
}

#pragma mark - QBImagePickerControllerDelegate
-(void)photoViewAddSubView
{
    CGRect arect = photoView.frame;
    arect.size.height = 80;
    photoView.frame = arect;
    
    arect = MymapView.frame;
    arect.origin.y = photoView.frame.origin.y+photoView.frame.size.height+15;
    MymapView.frame = arect;

    for (UIView *view in photoView.subviews) {
        if (view != addBtn) {
            [view removeFromSuperview];

        }
    }
    float thisx = 10;
    float thisy = 10;
     for (int i =0; i<imgArray.count; i++) {
         if (thisx>230) {
             thisx=10;
             thisy += 75;
             CGRect rect = MymapView.frame;
             rect.origin.y+= 75;
             MymapView.frame = rect;
             rect = photoView.frame;
             rect.size.height +=75;
             photoView.frame = rect;
         }
         UIImage *tempimage= [imgArray objectAtIndex:i];
         UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(thisx, thisy, 60, 60)];
         btn.tag = i+50;
         [btn addTarget:self action:@selector(photoTouched:) forControlEvents:UIControlEventTouchUpInside];
         [btn setImage:tempimage forState:UIControlStateNormal];
         [photoView addSubview:btn];
        // [imgArray addObject:btn];
         thisx+= 72;
         
         //                if (imgArray.count == 8) {
         //                    addBtn.hidden = YES;
         //                }
     }
    CGRect newrect = addBtn.frame;
    if (thisx > 230) {
        thisx = 10;
        thisy += 75;
        newrect.origin.x = thisx;
        newrect.origin.y = thisy;
        CGRect rect = MymapView.frame;
        rect.origin.y += 75;
        MymapView.frame = rect;
        rect = photoView.frame;
        rect.size.height += 75;
        photoView.frame = rect;
    }
    else
    {
        newrect.origin.x = thisx;
        newrect.origin.y = thisy;
        
    }
    addBtn.frame = newrect;

    self.ScrollView.contentSize = CGSizeMake(320, MymapView.frame.size.height+MymapView.frame.origin.y+15);
    
}
-(void)photoTouched:(UIButton *)sender
{
    
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    BOOL displayActionButton = YES;

    
    for (int i = 0; i< imgArray.count; i++) {
        photo = [MWPhoto photoWithImage:[imgArray objectAtIndex:i]];
        // photo.caption = @"Fireworks";
        [photos addObject:photo];
    }

    browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = displayActionButton;
    browser.zoomPhotosToFill = YES;
    browser.hiddenTopBtn = NO;
    [browser setCurrentPhotoIndex:sender.tag - 50];
    
    self.photos = photos;

   
    [self.navigationController pushViewController:browser animated:YES];
}
-(void)deleteBtnTouched:(int)sender
{
    [self.photos removeObjectAtIndex:sender];
  //  [self.photos removeLastObject];
    [imgArray removeObjectAtIndex:sender];
    
    myPublish.mImgArr  = imgArray;

    [self photoViewAddSubView];
}
#pragma mark - MWPhotoBrowserDelegate
- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index
{
    NSLog(@"%D",index);
    return YES;
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return imgArray.count;
}
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected
{
    NSLog(@"%d",index);
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}
#pragma QBimagePickerDelegate
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    
     //   static BOOL isAddFrame = NO;
       UIImage *tempImage = [info valueForKey:UIImagePickerControllerOriginalImage];


    if ([tempImage isKindOfClass:[UIImage class]]) {
        UIImageWriteToSavedPhotosAlbum(tempImage, nil, nil, nil);
      //  NSData *data = UIImageJPEGRepresentation(tempImage, 10.0f);
       // NSLog(@"length%D",data.length);
        [imgArray addObject:tempImage];
        myPublish.mImgArr  = imgArray;
        [self dismissViewControllerAnimated:YES completion:^{
            [self photoViewAddSubView];
        }];

        return;
    }
    if(imagePickerController.allowsMultipleSelection) {
        
      NSArray *mediaInfoArray = (NSArray *)info;
        NSLog(@"Selected %d photos and mediaInfoArray==%@", mediaInfoArray.count,mediaInfoArray);

        
       for (int i =0; i<mediaInfoArray.count; i++) {
           NSDictionary *dic = [mediaInfoArray objectAtIndex:i];
           UIImage *temp = [dic valueForKey:UIImagePickerControllerOriginalImage];
         //  NSData *adata = UIImageJPEGRepresentation(temp, 10.0f);
          // NSLog(@"length%D",adata.length);
           if (imgArray.count==9) {
               [SVProgressHUD showErrorWithStatus:@"最多只能选择9张"];
               [self dismissViewControllerAnimated:YES completion:^{
                   [self photoViewAddSubView];
                   
               }];

               return;
           }
           [imgArray addObject:temp];
       }
        myPublish.mImgArr  = imgArray;

    } else {
        NSDictionary *mediaInfo = (NSDictionary *)info;
        NSLog(@"Selected: %@", mediaInfo);
    }
  //  [self dismissViewControllerAnimated:YES completion:NULL];
    [self dismissViewControllerAnimated:YES completion:^{
        [self photoViewAddSubView];

    }];

}



- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    NSLog(@"取消选择");
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
